#include "mainwindow.h"

#include <QApplication>
#include "framework.h"
#include <QProcess>
#include "client/windows/handler/exception_handler.h"
#include <QFile>
#include <QDir>

static Framework *g_framework=nullptr;

//windbg.exe -y . -z dumps\{minidump_id}.dmp -c "kv" -logo dumps\{minidump_id}.txt
bool onMinidumpDumped(const wchar_t* dump_path,
                                   const wchar_t* minidump_id,
                                   void* context,
                                   EXCEPTION_POINTERS* exinfo,
                                   MDRawAssertionInfo* assertion,
                                   bool succeeded)
{
    if(succeeded)
    {
        QString path(QString::fromWCharArray(dump_path));
        path += '\\';
        path += QString::fromWCharArray(minidump_id);
        QString arguments(" -y . -z ");
        arguments += path;
        arguments += ".dmp -c \"kv\" -logo ";
        arguments += path;
        arguments += ".txt";
        QProcess p;
        p.start("windbg.exe" + arguments);

        qlonglong oldSize=0;
        while(true){
            QFile f(path+".txt");
            if(f.exists() && f.size() == oldSize && oldSize)
            {
                break;
            }
            oldSize =f.size();
            p.waitForFinished(100);
        }

    }
    return succeeded;
}

bool InitBreakpad()
{
    QDir dir;
    dir.mkpath("dumps");
    google_breakpad::ExceptionHandler *pCrashHandler =
        new google_breakpad::ExceptionHandler(L"dumps",
        nullptr,
        onMinidumpDumped,
        nullptr,
        google_breakpad::ExceptionHandler::HANDLER_ALL,
        MiniDumpNormal,
        static_cast<const wchar_t*>(nullptr),
        nullptr);

    if(pCrashHandler == nullptr) {
        return false;
    }

    return true;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    g_framework = new Framework();

    g_framework->readComDefinition("cns");
    CnsComponentPtr view = g_framework->getComponent("viewer", "/viewer/.//viewer");
    view->exec(view, "createView", Q_ARG(CnsComponentPtr, view));

    return a.exec();
}
